//some action
var dataDoor = {
    // host : "http://192.168.10.218:8080/",
    // hostPath: 'http://' + window.location.host+"/Score/",
    host: "/Score/",
    hostPath: "/Score/",
    info: "score/checkSupport.action",
    scoreInfo: "score/findScoreInfo.action",
    score: "score/importScoreFromSchool.action",
    getYzCode: "score/getVerCode.action",
    //cet
    getCetScore: "score/importScoreCet.action",
    //chinese
    getChineseProvince: "score/getMandarinForm.action",
    getChineseScore: "score/importScoreMandarin.action",
    //computer
    getComputerInfo: "score/getNcreForm.action",
    getComputerScore: "score/importScoreNcre.action",
    //addUserTicketnumber
    addUserTicketnumber: 'scoreticket/addUserTicketnumber.action',
    //ticketList
    ticketList: 'scoreticket/ticketList.action',
    //delTicket
    delTicket: 'scoreticket/delTicket.action',
    //share : "http://192.168.0.36:8080/Share/publish.action",
    bindRenren: "http://www.super.cn/Auth/rr_auth.php",
    bindWeibo: "http://112.124.57.135/Auth/auth.php",
    share: "http://112.124.56.216:8080/Share/publish.action",
    focus: "http://112.124.56.216:8080/Share/Weibo/followBiaoBiao.action",
    get: function(type, noHost) {
        var self = this;
        if (noHost) {
            return self[type];
        }
        return self.hostPath + self[type];
    }
}

//a simple selector
var $$ = function(ele) {
    var getElementsByClassName = function(searchClass, node, tag) {
        if (document.getElementsByClassName) {
            return document.getElementsByClassName(searchClass)
        } else {
            node = node || document;
            tag = tag || "*";
            var classes = searchClass.split(" "),
                elements = (tag === "*" && node.all) ? node.all : node.getElementsByTagName(tag),
                patterns = [],
                returnElements = [],
                current,
                match;
            var i = classes.length;
            while (--i >= 0) {
                patterns.push(new RegExp("(^|\\s)" + classes + "(\\s|$)"));
            }
            var j = elements.length;
            while (--j >= 0) {
                current = elements[j];
                match = false;
                for (var k = 0, kl = patterns.length; k < kl; k++) {
                    match = patterns[k].test(current.className);
                    if (!match) break;
                }
                if (match) returnElements.push(current);
            }
            return returnElements;
        }
    }
    var selectType = ele.substr(0, 1);
    if (selectType === ".") {
        return getElementsByClassName(ele.slice(1));
    } else if (selectType === "#") {
        return document.getElementById(ele.slice(1)) ? document.getElementById(ele.slice(1)) : null;
    } else {
        return null;
    }
};

//bind
var addEvent = function(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
    } else if (obj.attachEvent) {
        obj.attachEvent("on" + type, function(e) {
            return fn.call(obj, e);
        });
    } else {
        obj['on' + type] = fn;
    }
}

//ajax only async ie8+ for json
function ajax(settingObj) {
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    var url = settingObj.url;
    var data = formatObjString(settingObj.data);

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            //success
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status == 304) {
                if (settingObj.dataType && settingObj.dataType == 'json')
                //for ie8+ w3c
                    var res = JSON.parse(xmlhttp.responseText);
                else
                    var res = xmlhttp.responseText;
                settingObj.onsuccess(res);
            } else {
                //error
                settingObj.onerror()
            }
        }
    }

    if (settingObj.method.toLowerCase() == "get") {
        //get
        xmlhttp.open('GET', url + "?" + data, true);
        xmlhttp.send();

    }
    if (settingObj.method.toLowerCase() == "post") {
        //post
        xmlhttp.open('POST', url, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(data);
    }
}

//parameters format
function formatObjString(obj, noUrlEncode) {
    var res = "";
    if (noUrlEncode) {
        for (var i in obj) {
            res += i + "=" + obj[i] + "&";
        }
    } else {
        for (var i in obj) {
            var tmp = (obj[i] + "").replace(/\%/g, "%25");
            tmp = tmp.replace(/&/g, "%26");
            tmp = tmp.replace(/\+/g, "%2B");
            res += i + "=" + tmp + "&";
        }
    }
    return res.slice(0, -1);
}

//get the url search
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

//trim
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

//new a mask
/*mask and pop*/
var createMask = function() {
    //type  motai
    var mask;
    return function() {
        if (!mask) {
            // wrap = $$("#term-wrap");
            mask = document.createElement("div");
            mask.id = "mask";
            document.body.appendChild(mask)
        }
        mask.style.display = "block";
        var tableWrap = $$('#table-wrap');
        if (tableWrap != undefined) {
            $$('#table-wrap').style.height = document.getElementsByTagName("html")[0].clientHeight + 'px';
            $$('#table-wrap').style.overflow = "hidden";
        }
        return mask;
    }
}();

/* a simple layout set middle in the vertical with js (fixed)*/
function layoutVertical(popup) {
    popup.style.display = "block";
    var popupHeight = popup.clientHeight;
    var bodyHeight = document.body.clientHeight;
    if (popupHeight > bodyHeight) {
        document.body.style.height = popupHeight + 20 + "px";
        popup.style.top = "10px";
    } else {
        popup.style.marginTop = (-1) * popupHeight / 2 + "px";
    }
}

//toast for error
function toast(content, intervalTime, callBack) {
    var intervalTime = (intervalTime || 2) * 1000;
    if ($$("#toast")) {
        var toast = $$("#toast");
        toast.innerHTML = content;
        toast.style.display = "block";
    } else {
        var toast = document.createElement("toast");
        toast.innerHTML = content;
        toast.style.display = "block";
        toast.id = "toast";
        document.body.appendChild(toast);
    }
    setTimeout(function() {
        toast.style.display = "none";
        if (callBack)
            callBack();
    }, intervalTime)
}

function addClass(target, name) {
    target.className += " " + name;
}

function removeClass(target, name) {
    var reg = new RegExp('(\\s|^)' + name + '(\\s|$)');
    target.className = target.className.replace(reg, '');
}

function hasClass(target, name) {
    var reg = new RegExp(name);
    return reg.test(target.className);
}

//valid
var validate = {
    stuNum: '',
    stuNumPwd: '',
    yzcode: '',
    year: "^[0-9]{4}$",
    term: "^[1-9]{1,2}$",
    check: function(string, type) {
        var self = this;
        var reg = new RegExp(self[type]);
        if (reg.test(string)) {
            return true;
        }
        return false;
    }
}

/* autofocus */
function autoFocus(identity) {
    ajax({
        "url": dataDoor.get("focus", true),
        "method": "post",
        "data": {
            "identity": identity
        },
        "async": true,
        "onsuccess": function() {},
        "onerror": function() {}
    });
}

var share = {
    toBind: function(platform, identity, id) {
        var backUrl = location.origin + location.pathname + location.search + "%23" + platform;
        var param = {
            "identity": identity,
            "id": id,
            "successUrl": backUrl,
            "errorUrl": backUrl
        }
        var bindUrl = platform ? dataDoor.get("bindWeibo", true) : dataDoor.get("bindRenren", true);
        //console.log(bindUrl + "?" + formatObjString(param,true))
        location.href = bindUrl + "?" + formatObjString(param, true);
    },

    toShare: function(platform, identity, project, id) {
        var self = this;
        ajax({
            "url": dataDoor.get("share", true),
            "method": "post",
            "data": {
                "identity": identity,
                "type": platform,
                "project": project,
                "parameterJson": ''
            },
            "dataType": "json",
            "onsuccess": function(data) {
                if (data.code == 2) {
                    toast("信息过期，请重新绑定", 1.5, function() {
                        self.toBind(platform, identity, id);
                    });
                } else {
                    toast("分享成功", 1);
                }
            },
            "onerror": function() {
                toast("分享失败，请检查网络", 1.5);
            }
        });
    }

}

/* contact modify select with real select */

var SuperSelect = function(modify, real, callback) {
    this.modify = modify;
    this.modifyContent = "";
    this.real = real;
    this.callback = callback || function() {};
    this.isInit = false;
}


SuperSelect.prototype.init = function() {
    //callback when change
    //modify id and real id
    var that = this;
    if (!that.isInit) {
        var $modifyObj = $("#" + that.modify);
        var $realObj = $("#" + that.real);
        var realVal = $realObj.val();
        var realContent = $("#" + that.real + " option")[Math.max($realObj[0].selectedIndex, 0)].innerHTML;
        that.modifyContent = $modifyObj.html();
        $modifyObj.html(realContent);
        that.isInit = true;

        //change
        $realObj.on("change", function() {
            var realContent = $("#" + that.real + " option")[Math.max($realObj[0].selectedIndex, 0)].innerHTML;
            $modifyObj.html(realContent);
            that.callback($realObj.val())
        })
    }
}

/*SuperSelect.prototype.disable = function(){
   var that = this;
   $("#"+that.modify).addClass("disabled").html(that.modifyContent);
   $("#"+that.real).hide().val(0);
}

SuperSelect.prototype.able = function(){
   var that = this;
   $("#"+that.modify).removeClass("disabled");
   $("#"+that.real).show();
}

SuperSelect.prototype.reset = function(){
   var that = this;
   $("#"+that.modify).html(that.modifyContent);
   $("#"+that.real).val(0);
}*/